package com.carpool.request;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.os.AsyncTask;

import com.carpool.message.Convert;
import com.carpool.message.ReplyMessage;
import com.carpool.message.RequestMessage;

public class RequestImpl extends Request {

	@Override
	public void postRequest(RequestMessage rqst) {
		
		new MessagesTask(rqst).execute();

	}

	private class MessagesTask extends
			AsyncTask<RequestMessage, Void, ReplyMessage> {
		private static final String SERVLET_URL = "http://169.254.80.238:8080/carpooletservice/ServletApp";
		private RequestMessage m_postData = null;

		public MessagesTask(RequestMessage m_postData) {
			this.m_postData = m_postData;
		}

		@Override
		protected ReplyMessage doInBackground(RequestMessage... params) {
			// TODO Auto-generated method stub
			URL url = null;
			ReplyMessage message =null;
			HttpURLConnection httpurlconnection = null;
			try {
				url = new URL(SERVLET_URL);
				httpurlconnection = (HttpURLConnection) url.openConnection();
				httpurlconnection.setRequestMethod("POST");
				httpurlconnection.setRequestProperty("Content-Type",
						"text/xml; charset=UTF-8");
				httpurlconnection.setDoOutput(true);
				httpurlconnection.setDoInput(true);
				httpurlconnection.connect();

				DataOutputStream dos = new DataOutputStream(
						httpurlconnection.getOutputStream());
				StringBuffer sb = Convert.reguest(m_postData);
				byte[] xmlbyte = sb.toString().getBytes("UTF-8");
				dos.write(xmlbyte);
				dos.close();

				DataInputStream dis = new DataInputStream(
						httpurlconnection.getInputStream());
				message = Convert.receive(dis);

			} catch (Exception e) {
			} finally {
				if (httpurlconnection != null)
					httpurlconnection.disconnect();
			}
			return message;
		}

		@Override
		protected void onPostExecute(ReplyMessage rpl) {
			
			if (rpl!=null) {			
				RequestImpl.this.onReplyAvailable(rpl);
				
			} else {
				RequestImpl.this.onReplyNotAvailable( );
			}
		}

	}
}
